package com.dvdfe8.crochet.controlador;

import com.dvdfe8.crochet.modelo.entity.Cliente;
import com.dvdfe8.crochet.modelo.service.ClienteService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author David
 */
@Controller
@RequestMapping("/cliente")
public class ClienteController {

    @Autowired
    ClienteService clienteService;

    @RequestMapping("/")
    public String cliente(){
        return "redirect:listar";
    }
    
    @RequestMapping("/nuevo")
    public ModelAndView nuevo() {
        ModelAndView mav = new ModelAndView("cliente/edit");
        Cliente cliente = new Cliente();
        mav.addObject("cliente", cliente);
        return mav;
    }

    @RequestMapping("/editar")
    public ModelAndView editar(@RequestParam int id){
        ModelAndView mav = new ModelAndView("cliente/edit");
        Cliente cliente = clienteService.getClienteById(id);
        mav.addObject("cliente", cliente);
        return mav;
    }
    
    @RequestMapping("/crear")
    public String crear(@ModelAttribute Cliente cliente, BindingResult result) {
        if (result.hasErrors()) {
            return "redirect:nuevo";
        }
        clienteService.crear(cliente);

        return "redirect:listar";
    }

    @RequestMapping("/listar")
    public ModelAndView listar() {
        ModelAndView mv = new ModelAndView("cliente/listado");
        List<Cliente> clientes = clienteService.listarTodos();
        mv.addObject("clientes", clientes);
        return mv;
    }
    
    @RequestMapping("/mostrar")
    public ModelAndView mostrar(@RequestParam int id){
        ModelAndView mv = new ModelAndView("cliente/datos");
        Cliente cliente = clienteService.getClienteById(id);
        mv.addObject("cliente", cliente);       
        return mv;
    }

    @RequestMapping("/eliminar")
    public String eliminar(@RequestParam int id){
        Cliente cliente = clienteService.getClienteById(id);
        clienteService.eliminar(cliente);
        return "redirect:../listar";
    }
    
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, false));
    }
}
